#!encoding: utf-8

import re
import os
import socket
from flask import jsonify

class switch(object):
    '''
    参考: [READABLE SWITCH CONSTRUCTION WITHOUT LAMBDAS OR DICTIONARIES (PYTHON RECIPE)](http://code.activestate.com/recipes/410692/)
    '''
    def __init__(self, value):
        self.value = value
        self.fall = False

    def __iter__(self):
        """Return the match method once, then stop"""
        yield self.match
        raise StopIteration
    
    def match(self, *args):
        """Indicate whether or not to enter a case suite"""
        if self.fall or not args:
            return True
        elif self.value in args:
            self.fall = True
            return True
        else:
            return False

def makeJsonMsg(resultList):
    resultObj = {}
    for i in resultList:
        resultObj[i['name']] = i
    ## 返回json类型的数据
    return jsonify(resultObj)

def validate_ip(ip):
    ## 用正则验证ip
    return re.match('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', ip)

def validate_port(port):
    try:
        port = int(port)
        return True
    except Exception, e:
        return False

def validate_delay_time(delay_time):
    try:
        val = int(val)
        if val <= 0:
            return False
    except Exception, e:
        return False
    return True

def get_version():
    ## 当前文件的绝对路径(无当前文件名, 只有所在目录路径)
    pwd = os.path.abspath(os.path.dirname(__file__))
    ver_txt = os.path.join(pwd, 'version')
    pyadmin_ver = open(ver_txt).read().strip()
    return pyadmin_ver

def is_port_open(ip, port):
    '''
    function: 检测目标端口是否被占用
    使用方法 is_port_open('127.0.0.1', 5000)
    '''
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect((ip, int(port)))
        s.shutdown(2)
        return True
    except:
        return False